package com.cloudcc.mobile.view.dynamic.dynamic;

import android.app.AlertDialog;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList.DynamicEvent;
import com.cloudcc.cloudframe.bus.EventList.FavotiteDynamicEvent;
import com.cloudcc.cloudframe.bus.EventList.VoteDynamicEvent;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.model.DynamicModel;
import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreContainer;
import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreHandler;
import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreListViewContainer;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrClassicDefaultHeader;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrDefaultHandler;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrHandler;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.DynamicAdapter;
import com.cloudcc.mobile.entity.MyChatter;
import com.cloudcc.mobile.event.refresh.RefreshDynamicListEvent;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.DynamicControl;
import com.cloudcc.mobile.util.LoadingUtils;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.activity.MyWebActivity;
import com.cloudcc.mobile.view.activity.Myinformation;
import com.cloudcc.mobile.view.activity.UserInfoActivity;
import com.cloudcc.mobile.view.dynamic.DynamicActivity;
import com.cloudcc.mobile.view.main.fragment.BaseListFragment;
import com.cloudcc.mobile.view.mymodel.isshuaxin;
import com.cloudcc.mobile.view.web.IWebView;
import com.easemob.util.NetUtils;
import com.litesuits.android.log.Log;
import com.mypage.utils.NetStateUtils;
import com.mypage.utils.SaveTemporaryData;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 动态页面
 * 
 * @author seven
 * 
 */
/**
 * @author seven
 * 
 */
public abstract class DynamicFragment extends BaseListFragment implements
		IEventLife, LoadMoreHandler,
		DynamicAdapter.OnItemListener, PtrHandler,
		OnItemClickListener {
private String mEns = RunTimeManager.getInstance().getlanguage();
	public static boolean hasCheckFrist = false;

	@Bind(R.id.listview)
	public ListView mListView;

	@Bind(R.id.load_more_list_view_ptr_frame)
	public PtrFrameLayout mRefreshLayout;

	@Bind(R.id.load_more_list_view_container)
	public LoadMoreListViewContainer mLoadMoreLayout;

	@Bind(R.id.introduction)
	RelativeLayout mmm;

	@Bind(R.id.in_know)
	TextView iKnow;
	@Bind(R.id.zanwu_moreyt)
	FrameLayout zanwuj;

	protected DynamicControl mControl = new DynamicControl();

	protected DynamicAdapter mAdapter;

	@Override
	public void init() {
		SaveTemporaryData.detailDyamic = "";
        SaveTemporaryData.GeneralOne = true;
		initRefresh();
		initLoadMore();
		initRequestData();
	}

	/**
	 * 初始化刷新
	 */
	protected void initRefresh() {
		mRefreshLayout.setLoadingMinTime(1000);
		mRefreshLayout.setPtrHandler(this);
		PtrClassicDefaultHeader header = new PtrClassicDefaultHeader(mContext);
//		final MyHeader header = new MyHeader(getActivity());
//		int[] colors = getResources().getIntArray(R.array.google_colors);
//		header.setColorSchemeColors(colors);
//		header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
//		header.setPadding(0, DensityUtils.dpToPixel(mContext, 10), 0,
//				DensityUtils.dpToPixel(mContext, 5));
//		header.setPtrFrameLayout(mRefreshLayout);
		mRefreshLayout.setHeaderView(header);
		mRefreshLayout.addPtrUIHandler(header);
	}

	// 删除以后的刷新
	public void onEventMainThread(isshuaxin event) {
		initRequestData();
	}

	/**
	 * 初始化 加载更多
	 */
	protected void initLoadMore() {
		mLoadMoreLayout.setAutoLoadMore(true);
		mLoadMoreLayout.setOffsetSize(3);
		mLoadMoreLayout.useDefaultFooter();
		mLoadMoreLayout.setLoadMoreHandler(this);
	}

	/**
	 * 自动开启刷新请求数据
	 */
	protected void initRequestData() {
		mRefreshLayout.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshLayout.autoRefresh(true);
			}
		}, 150);
	}

	@Override
	public void onLoadMore(LoadMoreContainer loadMoreContainer) {
		currentPage++;
		requestData();
	}

	@Override
	public void requestData() {
		mControl.getDynamic(currentPage, getQueryType());
	}

	public abstract String getQueryType();

	/**
	 * 加载 动态（微贴）成功的时候
	 * <p>
	 * #1 判断是不是 这类型 是自己的 不要操作 <br>
	 * #2 判断是不是出错 如果出错 判断是不是第一次访问 如果第一次访问的话 就 结束
	 * <p>
	 * 
	 * @param event
	 */
	// 手指按下的点为(x1, y1)手指离开屏幕的点为(x2, y2)
	float x1 = 0;
	float x2 = 0;
	float y1 = 0;
	float y2 = 0;

	public void onEventMainThread(DynamicEvent event) {

		if (!StringUtils.equals(getQueryType(), event.type)) {
			return;
		}
		if (event.isError()) {
			if (isFromRefresh()) {
				mRefreshLayout.refreshComplete();
				zanwuj.setVisibility(View.VISIBLE);
//				mLoadMoreLayout.loadMoreFinish(true, false);
			} else {
				mLoadMoreLayout.loadMoreError(1002, event.getMessage());
			}
//			Toast.makeText(mContext, event.getMessage(), 0).show();
			return;
		}
		onRequestFinish(ListUtils.isEmpty(event.getData().data));
		if (mAdapter == null) {
			mAdapter = new DynamicAdapter(mContext);
			mListView.setAdapter(mAdapter);
			mListView.setOnItemClickListener(this);
			mAdapter.setOnItemtListener(this);
		}


			if (isFromRefresh()) {
				if(event.getData().data.size() == 0) {
				   zanwuj.setVisibility(View.VISIBLE);
				}else {
					zanwuj.setVisibility(View.INVISIBLE);
				}
				if (RunTimeManager.getInstance().getIsRefreshx()) {
					mAdapter.changeDatax(event.getData().data);
					RunTimeManager.getInstance().setIsRefreshx(false);
				} else {
					mAdapter.changeData(event.getData().data);
					android.util.Log.i("shuaxinla", "+++++++++++++++++++++++=");
					}
				} else{
					mAdapter.addData(event.getData().data);
					android.util.Log.i("shuaxinla", "+++++++++++++++++++++++++++++++++");
				}

			}
	protected void onRequestFinish(boolean dataIsEmpty) {

		if (isFromRefresh()) {// 第一次加载 获得的数据为空
			mRefreshLayout.refreshComplete();
			mLoadMoreLayout.loadMoreFinish(dataIsEmpty, !dataIsEmpty);
		} else {
			mLoadMoreLayout.loadMoreFinish(false, !dataIsEmpty);
		}
	}

	@Override
	public void onClickCollect(DynamicModel t) {
		mControl.Favorite(t.id, t.isfavorited);
	}

	public void onEventMainThread(FavotiteDynamicEvent event) {
		// ToastMananger.getManager().showOk("结果::" + event.isOk());
	}

	@Override
	public void onClickLike(DynamicModel t, View v) {
		mControl.like(t.id, t.ispraised);
	}

	@Override
	public void onClickDelete(DynamicModel t, int pos) {

		if (StringUtils.equals(t.authorId,
				UserManager.getManager().getUser().userId)) {
			showDialog(t, pos);
		}

	}

		@Override
	public void onClickUser(DynamicModel t) {
		enterUserInfo(t);
	}

	private void enterUserInfo(DynamicModel t) {
		Intent intent = new Intent(mContext,
				Myinformation.class);
		SaveTemporaryData.mSmart="";
		intent.putExtra(UserInfoActivity.KEY_USERID, t.authorId);
		intent.putExtra("name", t.authorIdname);
		startActivity(intent);
	}

	@Override
	public void onClickComment(DynamicModel t) {
		MyChatter covertBean = GsonUtil.covertBean(t, MyChatter.class);
		Intent intent = new Intent(getActivity(), DynamicActivity.class);
		intent.putExtra("myChatter", covertBean);
		startActivity(intent);
	}

	@Override
	public void onClickDownload(DynamicModel t, int position) {
		MyChatter covertBean = GsonUtil.covertBean(t, MyChatter.class);
		LoadingUtils loading = new LoadingUtils(mContext, covertBean, position);
		loading.loadingFile();
	}

	@Override
	public void onClickVote(DynamicModel t, String option) {

		createWainting();
		mControl.sendVote(t.id, option);
	}

	public void onEventMainThread(VoteDynamicEvent event) {
		dismissWainting();

		mAdapter.refreshVote();

	}

	@Override
	public void onClickRelation(DynamicModel t) {
		Log.d("dianjishijian", "zhuye点击关联事件");
		AppContext.urlString = UrlManager.getRootUrl()
				+ UrlTools.getObjectUrl_z(t.targetId);
		Intent intent = new Intent(mContext, BeauInfoActivity.class);
		intent.putExtra("web", t.targetId);
		if ((t.targetId.startsWith("bef")) || ((t.targetId.startsWith("bfa")))) {
			intent.putExtra(
					"web.url",
					UrlManager.getRootUrl()
							+ UrlTools.getObjectUrl_z(t.targetId));
		} else {
			intent.putExtra("web.url",
					UrlManager.getRootUrl() + UrlTools.getObjectUrl(t.targetId));
		}

		mContext.startActivity(intent);
	}

	@Override
	public void onClickBody(DynamicModel t) {
		Log.d("shibushidianji11", "协作详细页面");
		MyChatter covertBean = GsonUtil.covertBean(t, MyChatter.class);
		Intent intent = new Intent(getActivity(), DynamicActivity.class);
		intent.putExtra("myChatter", covertBean);
		startActivity(intent);
	}

	// 活动汇报记录（签到拜访）点击事件
	@Override
	public void onClickEventOrTask(DynamicModel t) {
		Intent intent = new Intent(mContext, BeauInfoActivity.class);
		intent.putExtra("web", t.taskIdOrEventId);
		if((t.taskIdOrEventId.startsWith("bef"))||((t.taskIdOrEventId.startsWith("bfa")))){
			intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl_z(t.taskIdOrEventId));
			intent.putExtra("from", "dynamicactivity");
		}else{
			intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl(t.taskIdOrEventId));
		}
		startActivity(intent);
		/*
		 * AppContext.urlString = UrlManager.APP_UR + "/" +
		 * UrlTools.getTaskOrEventUrl(t.taskIdOrEventId); Intent intent = new
		 * Intent(mContext, RelevantActivtiy.class); intent.putExtra("web",
		 * t.taskIdOrEventId); intent.putExtra("web.url", AppContext.urlString);
		 * mContext.startActivity(intent);
		 */
//		Intent intent = new Intent(mContext, CloudWebViewActivity.class);
//		intent.putExtra(ExtraConstant.EXTRA_URL, UrlManager.getManager()
//				.getTaskOrScheduleDetailUrl(t.taskIdOrEventId));
//		MonitorParam monitorParam = new MonitorParam(
//				new String[] { "m=delete" }, WebSyncDefaultProxy.STEP_START,
//				new String[] { "taskcondition=today", "m=list&objid=task",
//						"eventcondition=today" }, true,
//				WebSyncDefaultProxy.STEP_START);
//		MonitorParam monitorParam2 = new MonitorParam(
//				new String[] { "m=save" }, WebSyncDefaultProxy.STEP_START,
//				new String[] { "m=query" }, true,
//				WebSyncDefaultProxy.STEP_OVERRIDEURL);
//		MonitorParam monitorParam3 = new MonitorParam(new String[] {
//				"taskcondition=today", "eventcondition=today" },
//				WebSyncDefaultProxy.STEP_START, new String[] {
//						"taskcondition=today", "eventcondition=today" }, true,
//				WebSyncDefaultProxy.STEP_START);
//		monitorParam3.isCallBack = false;
//		intent.putExtra(
//				"callback",
//				WebSyncDefaultProxy
//						.creatDefaultProxy(ReceiverConstant.RECEIVE_REFRESH)
//						.addMonitorParam(monitorParam)
//						.addMonitorParam(monitorParam2)
//						.addMonitorParam(monitorParam3).addHomeMonitor());
//
//		startActivity(intent);
	}

	// 详情页面listview点击事件
	@Override
	public void onClickLink(DynamicModel t) {
		Intent intent = new Intent(mContext, MyWebActivity.class);
		intent.putExtra(IWebView.KEY_URL, t.linkValue);
		if ("en".equals(mEns)) {
			intent.putExtra(IWebView.KEY_NAME,
					StringUtils.isBlank(t.linkName) ? "Share links" : "Share links-" + t.linkName);
		}else{
			intent.putExtra(IWebView.KEY_NAME,
					StringUtils.isBlank(t.linkName) ? "分享链接" : "分享链接-" + t.linkName);
	}
		
		mContext.startActivity(intent);
	}

	class Ddialog {
		private TextView name;
		private Button cancle, sure;
	}

	protected void showDialog(final DynamicModel t, int pos) {
		final Ddialog dd = new Ddialog();
		LayoutInflater inflater = getActivity().getLayoutInflater();
		View layout = inflater.inflate(R.layout.define_deleted, null);
		dd.name = (TextView) layout.findViewById(R.id.titletitle);
		if ("en".equals(mEns)) {
			dd.name.setText("Are you sure you want to delete this post？");
		}else{
			dd.name.setText("确定删除这条微贴吗？");
	}

		final AlertDialog builder = new AlertDialog.Builder(getActivity())
				.create();
		builder.setView(layout,0,0,0,0);
		builder.show();
		Button cancle = (Button) layout.findViewById(R.id.quxiaocanle);
		cancle.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				builder.cancel();
			}
		});
		Button sure = (Button) layout.findViewById(R.id.quedingsure);
		sure.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(NetUtils.hasNetwork(mContext)){
					mControl.delete(t.id);
					mAdapter.removeItem(t);
					builder.cancel();
				}else {
					Toast.makeText(mContext,"删除失败,当前没有网络",Toast.LENGTH_SHORT).show();
					builder.cancel();
				}
			}
		});

	}

	@OnClick(R.id.in_know)
	public void clickKnow() {
		mmm.setVisibility(View.GONE);
		mRefreshLayout.setVisibility(View.VISIBLE);
		UserManager.getManager().saveFrist(false);
	}

	@Override
	public void onResume() {
		super.onResume();

		isFirst();
		register();
		initRequestData();
	}

	@Override
	public void onPause() {
		super.onPause();
		if (!NetStateUtils.isNetworkConnected(getActivity())){
			Toast.makeText(getActivity(),R.string.zanwus,Toast.LENGTH_SHORT).show();
		}
		mRefreshLayout.refreshComplete();

	}

	@Override
	public void register() {
		EventEngine.register(this);
	}
	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}

	private void isFirst() {

		if (hasCheckFrist) {
			return;
		}
		if (UserManager.getManager().isFrist()) {
			mmm.setVisibility(View.VISIBLE);
			mRefreshLayout.setVisibility(View.GONE);
		} else {
			mmm.setVisibility(View.GONE);
			mRefreshLayout.setVisibility(View.VISIBLE);
		}
		hasCheckFrist = true;
	}

	@Override
	public void onRefreshBegin(PtrFrameLayout arg0) {
		onRefreshData();
	}

	@Override
	public boolean checkCanDoRefresh(PtrFrameLayout frame, View content,
			View header) {
		return PtrDefaultHandler.checkContentCanBePulledDown(frame, mListView,
				header);
	}

//	private class MyHeader extends MaterialHeader {
//
//		public MyHeader(Context context) {
//			super(context);
//		}
//
//		public MyHeader(Context context, AttributeSet attrs, int defStyleAttr) {
//			super(context, attrs, defStyleAttr);
//		}
//
//		public MyHeader(Context context, AttributeSet attrs) {
//			super(context, attrs);
//		}
//
//		@Override
//		public void onUIRefreshComplete(PtrFrameLayout frame) {
//			super.onUIRefreshComplete(frame);
//		}
//	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		DynamicModel t = mAdapter.getItem(position);
		MyChatter covertBean = GsonUtil.covertBean(t, MyChatter.class);
		Intent intent = new Intent(getActivity(), DynamicActivity.class);
		intent.putExtra("myChatter", covertBean);
		startActivity(intent);
	}

	@Override
	public int getLayoutId() {
		return R.layout.dynamic_frag;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unRegister();
	}

	/**
	 * 发送消息
	 * 
	 * @param event
	 */
	public void onEventMainThread(RefreshDynamicListEvent event) {
		initRequestData();
	}
}
